package synchronization;

public class BankTransferRaceCondition {

	static class Account {
		private double ammount = 0;

		void setAmmount(double ammount) {
			this.ammount = ammount;
		}

		double getAmmount() {
			return this.ammount;
		}
	}

	static class Bank {
		// This method should be declared "synchronized"
		// to avoid the race conditions
		public static synchronized void deposit(Account acc, double ammount) {
			double oldAmmount = acc.getAmmount();
			 try {
				Thread.sleep(1000);
			} catch (InterruptedException ie) {
			}
			double newAmmount = oldAmmount + ammount;
			acc.setAmmount(newAmmount);
		}
	}

	public static void main(String[] args) throws InterruptedException {
		final Account acc = new Account();
		
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				Bank.deposit(acc, 100);
			}
		});
		t1.start();

		// Uncomment this to show that race condition is
		// impossible when data is accessed sequentually
		// t1.join();
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				Bank.deposit(acc, 200);
			}
		});
		t2.start();
		
		t1.join();
		t2.join();
		
		System.out.println("Ammount: " + acc.getAmmount());
	}

}
